﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Bee.Infrastructure
{
    /// <summary>
    /// xml
    /// </summary>
    public class XmlHepler
    {
        public static Logger logger = new Logger(typeof(XmlHepler));
        /// <summary>
        /// 将对象序列化成XML
        /// </summary>
        /// <typeparam name="T">实体泛型类</typeparam>
        /// <param name="filePath">保存文件地址</param>
        /// <param name="obj">实体对象</param>
        public static string Serialize<T>(T obj)
        {
            string result = string.Empty;
            try
            {
                MemoryStream stream = new MemoryStream();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(stream, obj);
                stream.Seek(0, SeekOrigin.Begin);
                TextReader tr = new StreamReader(stream);
                result = tr.ReadToEnd();
                tr.Close();
                stream.Close();
                return result;
            }
            catch (Exception e)
            {
                logger.Error("XML序列化出现异常", e);
                return result;
            }
        }

        /// <summary>
        /// xml反序列化
        /// </summary>
        /// <typeparam name="T">反序列化对象实例</typeparam>
        /// <param name="xml">xml数据</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            T obj = default(T);
            try
            {
                StringReader sr = new StringReader(xml);
                XmlReader xmlReader = new XmlTextReader(sr);
                Stream stream = IoHelper.StringToStream(xml);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                obj = (T)xmlSerializer.Deserialize(stream);
                obj = (T)xmlSerializer.Deserialize(xmlReader);
                return obj;
            }
            catch (Exception e)
            {
                logger.Error("XML反序列化出现异常", e);
                return obj;
            }
        }
    }
}
